package com.isoft.service.impl;

import com.isoft.entity.DfmeFrttEntity;
import com.isoft.mapper.DfmeFrttMapper;
import com.isoft.service.DfmeFrttService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeFrttServiceImpl implements DfmeFrttService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeFrttServiceImpl.class);

    @Autowired
    private DfmeFrttMapper dfmeFrttMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        // 1. 读取文件内容
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());

        // 2. 处理文件
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeFrttEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            // 1. 验证XML内容
            validateXmlContent(xmlContent);

            // 2. 解析XML
            DfmeFrttEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeFrttEntity.class);

            // 3. 验证解析结果
            validateEntity(entity);

            // 4. 处理并保存数据
            processFlightData(entity);

            return "Flight data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("XML processing failed", e);
            throw new RuntimeException("Failed to process XML: " + e.getMessage());
        }
    }

    private void validateXmlContent(String xmlContent) {
        if (xmlContent == null || xmlContent.trim().isEmpty()) {
            throw new IllegalArgumentException("XML content is empty");
        }

        // 确保包含必要的根元素
        if (!xmlContent.contains("<MSG>") || !xmlContent.contains("</MSG>")) {
            throw new IllegalArgumentException("Invalid XML structure: Missing <MSG> root element");
        }
    }

    private void validateEntity(DfmeFrttEntity entity) {
        // 增强空值检查
        if (entity.getMeta() == null) {
            logger.error("Meta data is missing after parsing");
            throw new IllegalArgumentException("Meta data is missing in XML");
        }

        if (entity.getDflt() == null) {
            logger.error("Flight data is missing after parsing");
            throw new IllegalArgumentException("Flight data is missing in XML");
        }

        // 验证必要的非空字段
        validateRequiredField(entity.getMeta().getSender(), "Sender");
        validateRequiredField(entity.getMeta().getDateTime(), "Meta dateTime");
        validateRequiredField(entity.getDflt().getFlightId(), "Flight ID");
        validateRequiredField(entity.getDflt().getScheduledTime(), "Scheduled time");
        validateRequiredField(entity.getDflt().getLatestTime(), "Latest time");
    }

    private void validateRequiredField(Object field, String fieldName) {
        if (field == null) {
            throw new IllegalArgumentException(fieldName + " is required");
        }

        if (field instanceof String && ((String) field).isBlank()) {
            throw new IllegalArgumentException(fieldName + " cannot be empty");
        }
    }

    private void processFlightData(DfmeFrttEntity entity) {
        try {
            logger.info("Processing flight data for flight ID: {}", entity.getDflt().getFlightId());

            // 1. 插入消息元数据
            dfmeFrttMapper.insertMeta(entity);
            logger.info("Inserted message meta data with ID: {}", entity.getMsgId());

            // 2. 插入航班基本信息，唯一性约束冲突时跳过
            try {
                int flightBaseCount = dfmeFrttMapper.insertFlightBase(entity);
                logger.info("Inserted {} flight base record", flightBaseCount);
            } catch (Exception e) {
                if (e.getMessage() != null && e.getMessage().contains("唯一性约束")) {
                    logger.warn("Flight base already exists for flight ID: {}, skipping insert.", entity.getDflt().getFlightId());
                } else {
                    throw e;
                }
            }

            // 3. 补充机场和航线（DFME-FRTT类型无机场字段，故跳过）
            // Long flightId = entity.getDflt().getFlightId();
            // String airportCode = "DEFAULT";
            // Integer airportSeq = 1;
            // String scheduledTime = entity.getDflt().getScheduledTime();
            // String estimatedTime = entity.getDflt().getLatestTime();
            // if (airportCode != null && !airportCode.trim().isEmpty()) {
            //     if (dfmeFrttMapper.checkAirportExists(airportCode) == 0) {
            //         dfmeFrttMapper.insertAirport(airportCode);
            //     }
            //     dfmeFrttMapper.insertFlightRoute(flightId, airportCode, airportSeq, scheduledTime, estimatedTime);
            // } else {
            //     logger.info("未检测到机场信息，跳过AIRPORT表和FLIGHT_ROUTE表插入");
            // }

            logger.info("Successfully processed flight data");
        } catch (Exception e) {
            logger.error("Error processing flight data for flight ID: {}",
                    entity.getDflt() != null ? entity.getDflt().getFlightId() : "unknown", e);
            throw new RuntimeException("Database operation failed: " + e.getMessage());
        }
    }
}